<template>
    <div class='self'>
        <div class='selfMain'>
            <el-form ref='selfFormRef' :model='selfFormValue' :rules='selfRules' label-width='140px' size='large'
                @submit.prevent>
                <el-form-item label='头像' prop='avatar' class='selfAvatarItem'>
                    <div class='avatarCon' @click='changeAvatar'>
                        <div class='selfAvatar'>
                            <img :src='selfFormValue.avatar || defAva' alt='' />
                        </div>
                        <div class='ceng'>
                            <span class='iconfont icon-jiahao1'></span>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label='姓名' prop='nick_name'>
                    <el-input @input="handleInputChange" v-model.trim='selfFormValue.nick_name' placeholder='请输入姓名' />
                </el-form-item>

                <el-form-item label="性别" prop='gender'>
                    <el-radio-group @change="handleInputChange" v-model="selfFormValue.gender">
                        <el-radio :value="1">男</el-radio>
                        <el-radio :value="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>


                <el-form-item label='手机号' prop='mobile'>
                    <el-input @input="handleInputChange" v-model.trim='selfFormValue.mobile' placeholder='请输入手机号' />
                </el-form-item>

                <el-form-item label='学校' prop='college'>
                    <el-input @input="handleInputChange" v-model.trim='selfFormValue.college' placeholder='请输入学校' />
                </el-form-item>

                <el-form-item label='学院' prop='arch_info'>
                    <el-input @input="handleInputChange" :disabled="true" v-model.trim='selfFormValue.arch_info' />
                </el-form-item>
                <!-- 这里只有学生角色可以展示，老师，管理员不展示 -->
                <div v-if="userStore.rolesName=='学生组'">
                    <el-form-item label='专业' prop='major'>
                        <el-input :disabled="true" v-model.trim='selfFormValue.major' />
                    </el-form-item>
                    <el-form-item label='班级' prop='class'>
                        <el-input :disabled="true" v-model.trim='selfFormValue.class' />
                    </el-form-item>

                    <el-form-item label='学号' prop='school_code'>
                        <el-input @input="handleInputChange" v-model.trim='selfFormValue.school_code' placeholder='请输入学号' />
                    </el-form-item>
                </div>
                <el-form-item>
                    <div class="buttons">
                        <el-button :disabled="isDisabled" type='primary' class='saveBtn' :loading="loadingRef" @click='saveForm'>
                            保存
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <el-dialog v-model='dialogVisible' title='上传头像' width='1000px' destroy-on-close>
            <CropperUser @avatarChange='avatarChange' :bkCover='selfFormValue.avatar'></CropperUser>
        </el-dialog>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import CropperUser from '@/components/CropperUser.vue';
import defAva from '@/assets/images/user-default.jpg';
import { Close } from '@element-plus/icons-vue';
import { getInfo, upUserInfo } from "@/api/login"

import useUserStore from '@/store/modules/user'
import { onMounted, watch } from 'vue';
const { proxy } = getCurrentInstance();
const loadingRef = ref(false)
const isDisabled = ref(true);
const dialogVisible = ref(false);
const userStore = useUserStore()
const selfFormValue = ref({
    user_id: '',
    avatar: '',
    nick_name: '',
    gender: null,
    mobile: "",
    college: "",
    arch_info: '',
    major: '',
    class: '',
    school_code: '',
    avatar_id:""
});
const avatarId=ref(null)
const isSuper=ref(userStore.is_super)

// 自定义手机号验证规则
const validatePhone = (rule, value, callback) => {
    const phonePattern = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    if (!value) {
        callback(new Error('手机号不能为空'));
    } else if (!phonePattern.test(value)) {
        callback(new Error('请输入正确的手机号格式'));
    } else {
        callback();
    }
};

//表结构验证规则
const selfRules = ref({
    nick_name: [
        { required: true, message: '姓名必须填写', trigger: 'blur' },
    ],
    mobile: [
        {
            required: true,
            validator: validatePhone, // 引用自定义的验证方法
            trigger: 'blur'
        }
    ],
    school_code: [
        { required: true, message: '学号必须填写', trigger: 'blur' },
    ],

});

//点击头像
const changeAvatar = () => {
    dialogVisible.value = true;
};

// 输入框内容改变
const handleInputChange=(v)=>{
    isDisabled.value=false  
}
//头像编辑完毕之后
const avatarChange = (e) => {

    dialogVisible.value = false;
    avatarId.value=e    
    let data = {
        "user": {'avatar_id':e}
    } 
    // 更新用户
    updateUserInfo(data)
};
// 更新用户
function updateUserInfo(data) {

    upUserInfo(data).then(res => {     
    if(!res&&data.user.nick_name){
        ElMessage.success('更新成功~~');
        isDisabled.value= true
        getUserInfo()
        loadingRef.value = false
        return
    }

    if(!res&&!data.user.nick_name){
        getUserInfo()
        loadingRef.value = false
        isDisabled.value= false
        return
    }

    ElMessage.error(res.response.data)    
    })
}
function trimQuotes(str) {
    const regex = /^"+|"+$/g;
    return str.replace(regex, '');
}
// 点击确认并保存更新用户
const saveForm = () => {
    proxy.$refs.selfFormRef.validate(valid => {
        selfFormValue.value.avatar_id=avatarId.value
        let data = {
            "user": selfFormValue.value
        }
        if (valid) {
            loadingRef.value = true  
            updateUserInfo(data)   
            userStore.avatar = selfFormValue.value.avatar
            userStore.userName = selfFormValue.value.nick_name
        } else {
            loadingRef.value = false
            ElMessage.error('请按照要求填写~~');
        }
    })


};

// 获取用户信息
const getUserInfo = () => {
    getInfo().then(res => { 
        console.log(res);
        if(!isSuper.value){
            res.user.arch_info=res.user.roles[0].parent_name
        }
        if(res.user.c_m_info.length){
            res.user.major=res.user.c_m_info[0].marjor_name
            res.user.class=res.user.c_m_info[0].cla_name

        }
       
        selfFormValue.value = res.user
    })
}


getUserInfo()


</script>


<style lang="scss" scoped>
.selfTitle {
    color: #2f2f2f;
    font-size: 24px;
    padding-left: 34px;
    line-height: 90px;
    width: 100%;
    border-bottom: 2px solid rgba(228, 228, 228, 1);
}

.selfMain {
    padding-top: 35px ;

    .buttons {
        padding: 10px 0 40px;
    }

    .space-line {
        display: flex;
        align-items: center;
        margin-bottom: 30px;

        .label {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            margin-right: 15px;
            font-size: 18px;
            color: rgba(51, 51, 51, 1);

            .iconfont {
                font-size: 20px;
                margin-right: 4px;
            }
        }

        .line {
            flex: 1;
            height: 1px;
            background-color: rgba(228, 228, 228, 1);
        }
    }

    .el-input {
        width: 300px;
    }

    .selfAvatarItem {
        display: flex;
        align-items: center;
    }

    .avatarCon {
        position: relative;
        width: 120px;
        height: 120px;
        border-radius: 50%;
        background: #eeeeee;
        cursor: pointer;
        overflow: hidden;

        .selfAvatar {
            width: 100%;
            height: 100%;

            img {
                width: 100%;
            }
        }
    }

    .ceng {
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        position: absolute;
        top: 0;
        left: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;
        transition: 0.3s;

        .iconfont {
            font-size: 40px;
        }
    }

    .avatarCon:hover .ceng {
        opacity: 1;
    }

    .resetPwd {
        color: #ff5733;
        font-size: 16px;
        cursor: pointer;
    }

    .tips {
        font-size: 13px;
        color: #888;
        margin-left: 24px;
    }

    .saveBtn {
        font-size: 14px;
    }

    :deep(.el-form-item__label) {
        padding-right: 24px;
    }

    .closeRest {
        margin-left: 20px;
    }
}
</style>